;(function($) {
	var $thisObj;
	loadJavaScriptAndCss();
	
	function loadJavaScriptAndCss() {
		$.ajaxSetup({async: false});
		loadRequiredJs();
		$.ajaxSetup({async: true});
		loadRequiredCss();
	}
	
	function loadRequiredJs() {
		loadJs(webContext + "/components/table/json2.js");
		loadJs(webContext + "/components/table/colResizable/colResizable-1.3.min.js");
	}

	/**
	 * 动态加载js文件
	 */
	function loadJs(jsPath) {
		if ($("script[src$=\"" + jsPath + "\"]").length == 0) {
			$.getScript(jsPath, function(data, textStatus, jqxhr) {});
		}
	}
	
	function loadRequiredCss() {
//		loadCss(webContext + "/js/commonTable/jquery.table.css");
	}
		
	function loadCss(cssHref) {
		if ($("link[href$=\"" + cssHref + "\"]").length == 0) {
			var styleTag = document.createElement("link");
			styleTag.setAttribute('type', 'text/css');
			styleTag.setAttribute('rel', 'stylesheet');
			styleTag.setAttribute('href', cssHref);
			$("head")[0].appendChild(styleTag);
		}
	}
	
	function getDefaultSettings() {
		return {
			 condition: {
			 	pageNo: 1,
			 	pageSize: 10
			 },
			 queryUrl: "",
			 pagingToolID: "", 							 //分页代码存放的标签ID
			 isMultiOrder: false,                        //是否可同时对多字段排序
			 allowAdjustColWidth: false,                  //是否允许调整列宽
			 onClickRow: null,                           //行项目点击时调用的回调方法
			 columns: [],
			 align: 'center',
			 width: "100%",
			 height: "100%"
		};
	}
	$.extend({
		"asLoadQueryMessage" : function($target,settings) {
			settings = $.extend(true,getDefaultSettings(), settings);
			this.$target = $target;
			this.$settings = settings;
			$thisObj = this;
			//查询等待
			$target.html(getWaitHtml(settings));
			loadQueryMessage(escape(JSON.stringify(settings)),1);
			return this;
		}
	});
	
	function loadQueryMessage(settings,pageNo) {
	
		var newSettings = unescape(settings);
		var settingsObj = "(" + newSettings + ")"; // 用括号将json字符串括起来        
		settingsObj = eval(settingsObj);
		//将排序列信息添加到请求参数中
		settingsObj = orderByFieldAddToCondition(settingsObj);
		var dataCondition = settingsObj.condition;
		dataCondition.pageNo = pageNo;
		
		$.ajax({
			type : "post",
			url : webContext + settingsObj.queryUrl,
			dataType : 'json',
			data : dataCondition,
			beforeSend : function(XMLHttpRequest) {
			},
			success : function(data, textStatus) {
				if(data.success) {
					var html = getTableHtml(data,$thisObj.$settings);
					$thisObj.$target.html(html);
					//绑定隔行变色、鼠标变小手时间
					changeColorOnMouseOverWithMultiTable();
					//给行项目绑定事件
					if($thisObj.$settings.onClickRow) {
						bindTrClickAction($thisObj.$settings);
					}
					//绑定初始化回调事件
					if($thisObj.$settings.onInit) {
						$thisObj.$settings.onInit();
					}
					//给排序字段绑定事件
					bindOrderByCellAction($thisObj.$settings);
					//是否允许拖动列的宽度
					if(settingsObj.allowAdjustColWidth) {
//						bindAdjustColWidthAction();
						bindColResizable();
					}
					//初始化时，修改列中隐藏文字的宽度
					initChangeColumnsWidth($thisObj.$settings);
					jqueryPageToolMethod(settings,pageNo,data,settingsObj.pagingToolID,"loadQueryMessage");
				}
			},
			complete : function(XMLHttpRequest, textStatus) {
			},
			error : function() {
				alert("error");
			}
		});
	}
	window.loadQueryMessage = loadQueryMessage;
	
	/**
	 * 给行项目绑定点击方法
	 */
	function bindTrClickAction(settings) {
		$(".greytable tr:gt(0)",$thisObj.$target).click(function(){
			settings.onClickRow(this);
		});
	}
	
	/**
	 * 给表头列名绑定排序方法
	 */
	function bindOrderByCellAction(settings) {
		for(var i=0;i<settings.columns.length;i++) {
			var columnObj = settings.columns[i];
			if(columnObj.isOrderByField) {
				$(".greytable tr:eq(0) td",$thisObj.$target).each(function() {
					if($(this).attr("columnName") == columnObj.name) {
						$(".table-head-cell-text",$(this)).click(function() {
							clickOrderByFiled(settings,$(this));
						});
					}
				});
			}
		}
	}
	
	/**
	 * 给表头排序列名执行方法
	 */
	function clickOrderByFiled(settings,thisObj) {
		var orderByType = "";
		
		if(thisObj.next().hasClass("table-head-cell-sort-desc")) {
			thisObj.next().removeClass("table-head-cell-sort-desc");
			thisObj.next().addClass("table-head-cell-sort-asc");
			orderByType = "asc";
		} else {
			thisObj.next().removeClass("table-head-cell-sort-asc");
			thisObj.next().addClass("table-head-cell-sort-desc");
			orderByType = "desc";
		}
		//如果为单字段排序
		if(!settings.isMultiOrder) {
			thisObj.parent().siblings().find("span:eq(1)").removeClass().end().addClass("table-head-cell-sort");
		} 
		changeOrderByType(settings,thisObj.parent().attr("columnName"),orderByType);
	}
	
	/**
	 * 修改列中的排序方式
	 */
	function changeOrderByType(settings,orderByName,orderByType) {
		for(var i=0;i<settings.columns.length;i++) {
			var columnObj = settings.columns[i];
			if(columnObj.name==orderByName) {
				columnObj.orderBy = orderByType;
			} else {
				//如果为单字段排序,将orderBy设置成非asc、desc就表示该字段不参与排序
				if(!settings.isMultiOrder) {
					columnObj.orderBy = "null";
				}
			}
		}
		var pageNo = 1;
		if($(".pagesel",$("#"+settings.pagingToolID)).length>0) {
			pageNo = parseInt($(".pagesel",$("#"+settings.pagingToolID)).html(),10);
		}
		loadQueryMessage(escape(JSON.stringify(settings)),pageNo);
	}
	
	/**
	 * 给请求参数中添加排序列信息
	 */
	function orderByFieldAddToCondition(settings) {	
		var orderByTableAliasArr = new Array();
		var orderByFieldArr = new Array();
		var orderByTypeArr = new Array();
		
		for(var i=0;i<settings.columns.length;i++) {
			var columnObj = settings.columns[i];
			var tableAlias =  "null";
			if(columnObj.isOrderByField) {
				if(columnObj.orderBy && (columnObj.orderBy=="asc" || columnObj.orderBy=="desc")) {
					if(columnObj.tableAlias) {
						tableAlias = columnObj.tableAlias;
					}
					orderByTableAliasArr.push(tableAlias);
					orderByFieldArr.push(columnObj.name);
					orderByTypeArr.push(columnObj.orderBy);
				}
			}
		}
		var orderByTableAlias = orderByTableAliasArr.join(",");
		var orderByFields = orderByFieldArr.join(",");
		var orderByTypes = orderByTypeArr.join(",");
		
		var dataCondition = settings.condition;
		dataCondition.orderByTableAlias = orderByTableAlias;
		dataCondition.orderByFields = orderByFields;
		dataCondition.orderByTypes = orderByTypes;
		
		return settings;
	}
	
	function getWaitHtml(settings) {
		var html = "<table align='"+settings.align+"' width='"+settings.width+"' border='0' cellpadding='0' cellspacing='1' class='greytable box'>";
		var titleHtml = getTitleHtml(settings);
		
		var colspan = settings.columns.length;
		var waitHtml = "<tr>";
		waitHtml += "<td align='center' colspan='"+colspan+"'><img src='" +webContext+ "/themed/images/05043118.gif' width='16' height='16' />数据加载中...</td>";
		waitHtml += "</tr>";
		html += titleHtml+waitHtml+"</table>";
		return html;
	}
	function getTableHtml(data,settings) {
		var html = "<table align='"+settings.align+"' width='"+settings.width+"' border='0' cellpadding='0' cellspacing='1' class='greytable box'>";
		var titleHtml = getTitleHtml(settings);
		var dataHtml = getDataHtml(data,settings);
		html += titleHtml+dataHtml+"</table>";
		return html;
	}
	
	function getTitleHtml(settings) {
		var titleHtml = "<tr>";
		
		for(var i=0;i<settings.columns.length;i++) {
			var columnObj = settings.columns[i];
			titleHtml += "<td class='ttd' ";
			//设置td内的属性信息 start
			if(columnObj.display && columnObj.display=="none") {
				titleHtml += "style=\"display:none\" ";
			}
			if(columnObj.width) {
				titleHtml += "width='"+columnObj.width+"' ";
			}
			if(columnObj.align) {
				titleHtml += "align='"+columnObj.align+"' ";
			}
			titleHtml += "columnIndex='"+parseInt(i)+"' columnName='"+columnObj.name+"'";
			//设置td内的属性信息 end
			titleHtml += ">";
			if(columnObj.isOrderByField) {
				titleHtml += "<span class='table-head-cell-text'>"+columnObj.tableHeader+"</span>";
				if(columnObj.orderBy=="desc") {
					titleHtml += "<span class='table-head-cell-sort-desc'>&nbsp;&nbsp;</span>";
				} else if(columnObj.orderBy=="asc") {
					titleHtml += "<span class='table-head-cell-sort-asc'>&nbsp;&nbsp;</span>";
				} else {
					titleHtml += "<span class='table-head-cell-sort'>&nbsp;&nbsp;</span>";
				}
			} else {
				titleHtml += "<span>"+columnObj.tableHeader+"</span>";
			}
			titleHtml += "</td>";
		}
		titleHtml += "</tr>";
		return titleHtml;
	}
	
	function getDataHtml(data,settings) {
		var dataHtml = "";
		if(data.data.length>0) {
			for(var j=0;j<data.data.length;j++) {
				var dataJson = data.data[j];
				dataHtml += "<tr ";
				if(settings.rowAttr) {
					dataHtml += settings.rowAttr.name+"='"+dataJson[settings.rowAttr.forJson]+"' ";
				}
				dataHtml += ">";
				for(var a=0; a<settings.columns.length; a++) {
					var columnObj = settings.columns[a];
					var text = dataJson[columnObj.name];
					if(columnObj.defaultValue) {//如果列给定了默认值，则直接使用默认值
						text = columnObj.defaultValue;
					}
					
					if(columnObj.emptyDefaultValue) {//为空或者为null时显示的值
						if(DF_Trim(text)=="" || DF_Trim(text)=="null") {
							text = columnObj.emptyDefaultValue;
						}
					}
					
					dataHtml += "<td ";
					//设置td内的属性信息 start
					if(columnObj.titleArr) {
						dataHtml += "title='"+text+"' algin='left' ";
						text = "<div class='elidetd_new' style='text-align:left'>"+text+"</div>"
					}
					if(columnObj.display && columnObj.display=="none") {
						dataHtml += "style=\"display:none\" ";
					}
					if(columnObj.id) {
						dataHtml += "id='"+columnObj.id+"' ";
					}
					//设置td内的属性信息 end
					dataHtml += ">" + text + "</td>";
				}
				dataHtml += "</tr>";
			}
		} else {
			dataHtml += "<tr>";
			var cells = settings.columns.length;
			dataHtml += "<td colspan='"+cells+"'>暂无数据！</td>";
			dataHtml += "</tr>";
		}
		return dataHtml;
	}
	
	//公共的分页方法
	function jqueryPageToolMethod(condition,pageNo,data,pageToolDiv,functionName) {
		//分页器
		if(data.totalPageCount > 1){
			$("#"+pageToolDiv).show();
	           $("#"+pageToolDiv).html(PagingToolV2.getPagingCode('bottomgo'+functionName,condition, functionName, data.totalPageCount,data.totalCount, pageNo));
		       $("#bottomgo"+functionName).keydown(function(event){
	                   if(event.keyCode==13){
	                     if(parseInt($("#bottomgo"+functionName).val())!=NaN){
	                     	 if(data.totalPageCount<parseInt($("#bottomgo"+functionName).val())){
	                     	     parseInt($("#bottomgo"+functionName).val(data.totalPageCount))
	                     	 }
	                       	 eval(functionName+"('"+condition+"',parseInt($('#bottomgo"+functionName+"').val()))+';'");
	                     }
	                   }
	            });
	    }else{
	    	$("#"+pageToolDiv).hide();
	    }
	}
	
	function DF_Trim(ss){
	  return ss.replace(/(^[\s]*)|([\s]*$)/g, "");
	}
	
	//鼠标拉动列宽=======================start
	function bindColResizable() {
		$(".greytable",$thisObj.$target).colResizable({
			liveDrag:true, 
			//gripInnerHtml:"<div class='grip'></div>", 
			draggingClass:"dragging", 
			minWidth:30,
			onResize:onSampleResized
		});
	}
	
	var onSampleResized = function(e){
		var widthArr = new Array();
		var columns = $(e.currentTarget).find("tr:eq(0) td");
		columns.each(function(){ 
			widthArr.push($(this).width());
		})
		changeColumnsWidth($thisObj.$settings,widthArr);
	};	
	
	/**
	 * 拖动表格列时，修改配置中相关列中的宽度
	 */
	function changeColumnsWidth(settings,newWidths) {
		for(var i=0;i<settings.columns.length;i++) {
			var columnObj = settings.columns[i];
			columnObj.width = newWidths[i] + "px";
			if(columnObj.titleArr) {
				var column = i+1;
				var width = parseInt(newWidths[i])-20 < 0 ? 20: parseInt(newWidths[i])-20;
				var newCss = {"width":width + "px","padding-left":"10px"};
				$(".greytable tr td:nth-child("+column+")",$thisObj.$target).find(".elidetd_new").css(newCss)
			}
		}
	}
	
	/**
	 * 初始化时，修改列中隐藏文字的宽度
	 */
	function initChangeColumnsWidth(settings) {
		for(var i=0;i<settings.columns.length;i++) {
			var columnObj = settings.columns[i];
			if(columnObj.titleArr) {
				var column = i+1;
				var $tdsObj = $(".greytable tr td:nth-child("+column+")",$thisObj.$target);
				$tdsObj.each(function() {
					var tdRealWidth = this.offsetWidth;
					var newCss = {"width":parseInt(tdRealWidth)-20 + "px","padding-left":"10px"};
					$(this).find(".elidetd_new").css(newCss)
				});
			}
		}
	}
	
	
	function bindAdjustColWidthAction() {
		
		$(".greytable tr:eq(0) td",$thisObj.$target).mouseup(function() {
			this.mouseDown = false;
		});
		
		$(".greytable tr:eq(0) td",$thisObj.$target).mousemove(function() {
			SyDG_moveOnTd(this);
		});
		
		$(".greytable tr:eq(0) td",$thisObj.$target).mousedown(function() {
			SyDG_downOnTd(this);
		});
		
		$(".greytable tr:eq(0) td",$thisObj.$target).mouseout(function() {
			this.mouseDown=false;
		});
	}
	function SyDG_moveOnTd(td)
	{
		if(event.offsetX>td.offsetWidth-10) {
			td.style.cursor='w-resize';
		} else {
			td.style.cursor='default';
		}
		if(td.mouseDown!=null && td.mouseDown==true)
		{
			if(td.oldWidth+(event.x-td.oldX)>0) {
				td.width=td.oldWidth+(event.x-td.oldX);
			}
			td.style.width=td.width;
			td.style.cursor='w-resize';
			
			table=td;
			while(table.tagName!='TABLE') {
				table=table.parentElement;
			}
			table.width=td.tableWidth+(td.offsetWidth-td.oldWidth);
			table.style.width=table.width;
		}
	}
	function SyDG_downOnTd(td)
	{
		if(event.offsetX>td.offsetWidth-10)
		{
			td.mouseDown=true;
			td.oldX=event.x;
			td.oldWidth=td.offsetWidth;
			table=td;while(table.tagName!='TABLE')table=table.parentElement;
			td.tableWidth=table.offsetWidth;
		}
	}
	//鼠标拉动列宽=======================end
})(jQuery);